package com.strategy.demo2;

import com.strategy.demo2.impl.MT1101ReceiptService;
import com.strategy.demo2.impl.MT2101ReceiptService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 定义策略 工厂类
 */
public class ReceiptFactory {


    /**
     * 声明 map工厂类
     */
    public static Map<String, ReceiptService> receiptServiceMap = new ConcurrentHashMap<>();

    /**
     * 声明可以 两种方式 一种是 动态代码块
     * 一种是 构造函数
     * 还有就是 定义 init方法
     * 后两种 构建 在 不使用的时候 不会创建  节省服务器的资源
     */
    static {
        receiptServiceMap.put("MT1101", new MT1101ReceiptService());
        receiptServiceMap.put("MT2101", new MT2101ReceiptService());

        SAXReader reader = new SAXReader();
        String file = null;
        if (file != null) {
            try {
                Document document = reader.read(file);
                //获取 xml文件中 config下的 className标签
                Node node = document.selectSingleNode("/config/className");
                //获取里面的内容
                String className = node.getText();
                //获取name对应的名称
                String name = node.getName();

                Class<?> forName = Class.forName(className);
                ReceiptService receiptService = (ReceiptService) forName.newInstance();
                receiptServiceMap.put(name, receiptService);

            } catch (DocumentException | ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }

    }

    public static void addReceiptService(String type, ReceiptService receiptService) {
        receiptServiceMap.put(type, receiptService);
    }
}
